package ltd.nullpointer.frontend.facade;

import com.boot2.core.exception.BusinessException;
import com.boot2.core.utils.SpringUtil;
import com.boot2.core.utils.StringUtils;
import lombok.extern.apachecommons.CommonsLog;
import org.apache.commons.lang3.reflect.MethodUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationTargetException;

/**
 * @author zhangweilin
 * @Description: xxxxx
 * @date 2019/12/15
 */
@Component
@CommonsLog
public class TCPComponentsFacade {

    /**
     * 将所有上报的数据全部持久化入库
     *
     * @param object
     */
    @Async
    public void save(Object object) {
        log.info("持久化报文组件2: " + object);
        //如果是需要持久化的，直接持久化
        Class<?> clazz = object.getClass();
        String simpleName = clazz.getSimpleName();
        simpleName = StringUtils.changFirstWord(simpleName, StringUtils.toLowerCase);
        Object dao = SpringUtil.getBean(simpleName + "Dao");
        try {
            MethodUtils.invokeMethod(object, "setCreateTime");
            MethodUtils.invokeMethod(dao, "saveAndFlush", object);
        } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
            e.printStackTrace();
            throw new BusinessException("保存上报数据失败", e);
        }
    }
}
